import 'package:flutter/material.dart';

import 'chat_model.dart';
import 'search_bar.dart';

class SearchPage extends StatefulWidget {
  final List<ChatModel> datas;
  const SearchPage({Key? key, required this.datas}) : super(key: key);

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  List<ChatModel> _models = [];
  String _searchStr = '';
  _searchModels(String text) {
    _searchStr = text;
    _models.clear();
    if (text.isNotEmpty) {
      for (int i = 0; i < widget.datas.length; i++) {
        if (widget.datas[i].username.contains(text)) {
          _models.add(widget.datas[i]);
        }
      }
    }
    setState(() {});
  }

  Widget _highlightUsername(String name) {
    TextStyle normal = TextStyle(color: Colors.black);
    TextStyle highlight = TextStyle(color: Colors.green);
    List<TextSpan> spans = [];
    List<String> strs = name.split(_searchStr);
    
    for (int i = 0; i < strs.length; i++) {
      String str = strs[i];
      if (str == '' && i < strs.length-1) {
        spans.add(TextSpan(text: _searchStr, style: highlight));
      }else {
        spans.add(TextSpan(text: str, style: normal));
        if (i < strs.length-1) {
          spans.add(TextSpan(text: _searchStr, style: highlight));
        }
      }
    }
    return RichText(text: TextSpan(children: spans));
  }

  Widget _buildItemForRow(BuildContext context, int index) {
    return ListTile(
      title: _highlightUsername(_models[index].username),
      subtitle: Container(
        width: 20,
        height: 20,
        child: Text(_models[index].message, overflow: TextOverflow.ellipsis,),
      ),
      leading: CircleAvatar(
        backgroundImage: NetworkImage(_models[index].imageUrl),
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          SearchBarText(inputText: (inputText) {
            //print("输入框输入的：$inputText");
            _searchModels(inputText);
          }),
          Expanded(
            child: MediaQuery.removePadding( //移除安全区
              removeTop: true,
              context: context,
              child: NotificationListener(
                onNotification: (ScrollNotification noti) {
                  if (noti is ScrollStartNotification) {
                    // print("开始滚动"); //收键盘
                    FocusScope.of(context).requestFocus(FocusNode());
                  }else if (noti is ScrollUpdateNotification) {
                    // print("正在滚动${noti.metrics.maxScrollExtent}---${noti.metrics.pixels}");
                  }else if (noti is ScrollEndNotification) {
                    // print("结束滚动");
                  }
                  return true;
                },
                child: ListView.builder(
                    itemCount: _models.length,
                    itemBuilder: _buildItemForRow
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
/*
    TextStyle normalStyle = const TextStyle(fontSize: 16, color: Colors.black);
    TextStyle highlightStyle = const TextStyle(fontSize: 16, color: Colors.green);

    List<TextSpan> spans = [];
    List<String> strs = name.split(_searchStr);
    for (int i = 0; i < strs.length; i++) {
      String str = strs[i];
      //遇见空串就加高亮，遇见字符后面加高亮，结尾处字符不加高亮
      if (str == '' && i < strs.length - 1) {
        spans.add(TextSpan(text: _searchStr, style: highlightStyle));
      } else {
        spans.add(TextSpan(text: str, style: normalStyle));
        if (i < strs.length - 1) {
          spans.add(TextSpan(text: _searchStr, style: highlightStyle));
        }
      }
    }
    return RichText(text: TextSpan(children: spans),);
 */

/**
 * Dart语法在线练习
 * https://www.tutorialspoint.com/execute_dart_online.php
 *
 */

/*
  List<String> strs = "hahahaaah".split('h');
  print(strs.length);
  for (int i = 0; i < strs.length; i++) {
      print("-${strs[i]}-");
  }
 */